{% extends "base.html" %}

{% block title %}设备销库{% endblock %}

{% block content %}
<div class="container-xl py-4">
    <h2 class="page-title">设备销库</h2>
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-trash-alt me-2"></i>设备销库</h5>
                </div>
                <div class="card-body">
                    <!-- SN码输入区域 -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">输入SN码</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="sn" class="form-label">SN码</label>
                                        <input type="text" class="form-control" id="sn" placeholder="请输入SN码">
                                    </div>
                                    <button class="btn btn-primary" id="addSn">添加</button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">批量导入</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="csvFile" class="form-label">CSV文件</label>
                                        <input type="file" class="form-control" id="csvFile" accept=".csv">
                                    </div>
                                    <button class="btn btn-primary" id="importSn">导入</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- SN码列表 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0">待查询SN码列表</h6>
                        </div>
                        <div class="card-body">
                            <div id="snList" class="mb-3">
                                <!-- SN码列表将在这里动态生成 -->
                            </div>
                            <button class="btn btn-primary" id="searchEquipment">查询设备</button>
                        </div>
                    </div>
                    
                    <!-- 查询结果 -->
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">查询结果</h6>
                        </div>
                        <div class="card-body">
                            <div id="searchResult" class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th><input type="checkbox" id="selectAll"></th>
                                            <th>入库时间</th>
                                            <th>SN码</th>
                                            <th>设备型号</th>
                                            <th>制造商</th>
                                            <th>当前网元</th>
                                            <th>新网元名称</th>
                                            <th>类型</th>
                                            <th>制式</th>
                                            <th>状态</th>
                                        </tr>
                                    </thead>
                                    <tbody id="equipmentList">
                                        <!-- 查询结果将在这里动态生成 -->
                                    </tbody>
                                </table>
                            </div>
                            <div id="searchStatus" class="mt-3">
                                <!-- 查询状态信息将在这里显示 -->
                            </div>
                            <button class="btn btn-success mt-3" id="confirmDiscard" disabled>确认销库</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<!-- 添加 jQuery 库 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        let snList = [];
        let selectedEquipment = [];
        
        // 添加SN码
        $('#addSn').on('click', function() {
            const sn = $('#sn').val().trim();
            if (sn) {
                if (!snList.includes(sn)) {
                    snList.push(sn);
                    updateSnList();
                    $('#sn').val('');
                } else {
                    alert('该SN码已添加');
                }
            }
        });
        
        // 导入CSV文件
        $('#importSn').on('click', function() {
            console.log('Import button clicked');
            const file = $('#csvFile')[0].files[0];
            if (!file) {
                alert('请选择CSV文件');
                return;
            }

            if (!file.name.toLowerCase().endsWith('.csv')) {
                alert('请选择CSV格式的文件');
                return;
            }

            console.log('File selected:', file.name);

            // 创建FormData对象
            const formData = new FormData();
            formData.append('csv_file', file);

            // 显示加载状态
            $('#searchStatus').html('<div class="alert alert-info">正在导入CSV文件...</div>');

            // 发送文件到后端处理
            $.ajax({
                url: '/batch_discard',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        // 更新SN码列表
                        const newSnList = response.equipment_list.map(item => item.sn);
                        snList = [...snList, ...newSnList];
                        updateSnList();

                        // 显示匹配的设备信息
                        const equipmentList = $('#equipmentList');
                        equipmentList.empty();
                        
                        response.equipment_list.forEach(item => {
                            const row = `
                                <tr>
                                    <td><input type="checkbox" class="equipment-checkbox" data-sn="${item.sn}"></td>
                                    <td>${item.date}</td>
                                    <td>${item.sn}</td>
                                    <td>${item.model || ''}</td>
                                    <td>${item.manufacturer || ''}</td>
                                    <td>${item.network_element || ''}</td>
                                    <td>
                                        <input type="text" class="form-control new-network-element" 
                                               data-sn="${item.sn}" value="${item.new_network_element || ''}" required>
                                    </td>
                                    <td>${item.type || ''}</td>
                                    <td>${item.standard || ''}</td>
                                    <td>${item.status || ''}</td>
                                </tr>
                            `;
                            equipmentList.append(row);
                        });

                        // 启用确认销库按钮
                        $('#confirmDiscard').prop('disabled', false);

                        // 更新状态信息
                        $('#searchStatus').html(`
                            <div class="alert alert-success">
                                ${response.message}<br>
                                请检查设备信息，确认无误后点击"确认销库"按钮。
                            </div>
                        `);
                    } else {
                        $('#searchStatus').html('<div class="alert alert-danger">' + response.message + '</div>');
                    }
                },
                error: function(xhr) {
                    const error = xhr.responseJSON || { message: '导入失败，请重试' };
                    $('#searchStatus').html('<div class="alert alert-danger">' + error.message + '</div>');
                    console.error('Error:', error);
                }
            });
        });
        
        // 更新SN码列表显示
        function updateSnList() {
            const snListElement = $('#snList');
            snListElement.empty();
            snList.forEach((sn, index) => {
                const badge = $('<span>')
                    .addClass('badge bg-primary me-2 mb-2')
                    .html(`
                        ${sn}
                        <button type="button" class="btn-close btn-close-white ms-2" 
                                onclick="removeSn(${index})" style="font-size: 0.5rem;"></button>
                    `);
                snListElement.append(badge);
            });
        }
        
        // 移除SN码
        window.removeSn = function(index) {
            snList.splice(index, 1);
            updateSnList();
        };
        
        // 查询设备
        $('#searchEquipment').on('click', function() {
            if (snList.length === 0) {
                alert('请先添加SN码');
                return;
            }
            
            $('#searchStatus').html('<div class="alert alert-info">正在查询...</div>');
            $('#equipmentList').empty();
            $('#confirmDiscard').prop('disabled', true);
            
            $.ajax({
                url: '/search_discard_equipment',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ sn_list: snList }),
                success: function(response) {
                    if (response.success) {
                        if (response.equipment.length > 0) {
                            const equipmentList = $('#equipmentList');
                            response.equipment.forEach(equipment => {
                                const row = $('<tr>').html(`
                                    <td><input type="checkbox" class="equipment-checkbox" 
                                             data-sn="${equipment.sn}"></td>
                                    <td>${equipment.date}</td>
                                    <td>${equipment.sn}</td>
                                    <td>${equipment.model}</td>
                                    <td>${equipment.manufacturer}</td>
                                    <td>${equipment.network_element}</td>
                                    <td><input type="text" class="form-control new-network-element" 
                                             data-sn="${equipment.sn}" placeholder="请输入新网元名称"></td>
                                    <td>${equipment.type}</td>
                                    <td>${equipment.standard}</td>
                                    <td>${equipment.status}</td>
                                `);
                                equipmentList.append(row);
                            });
                            $('#confirmDiscard').prop('disabled', false);
                        } else {
                            $('#searchStatus').html(
                                '<div class="alert alert-warning">未找到匹配的设备</div>'
                            );
                        }
                    } else {
                        $('#searchStatus').html(
                            `<div class="alert alert-danger">${response.message}</div>`
                        );
                    }
                },
                error: function(error) {
                    $('#searchStatus').html(
                        '<div class="alert alert-danger">查询失败，请稍后重试</div>'
                    );
                    console.error('Error:', error);
                }
            });
        });
        
        // 全选/取消全选
        $('#selectAll').on('change', function() {
            $('.equipment-checkbox').prop('checked', this.checked);
        });
        
        // 确认销库
        $('#confirmDiscard').on('click', function() {
            const selectedEquipment = $('.equipment-checkbox:checked').map(function() {
                const sn = $(this).data('sn');
                const newNetworkElement = $(`.new-network-element[data-sn="${sn}"]`).val().trim();
                if (!newNetworkElement) {
                    alert(`请为设备 ${sn} 输入新网元名称`);
                    return null;
                }
                return {
                    sn: sn,
                    new_network_element: newNetworkElement
                };
            }).get().filter(item => item !== null);
            
            if (selectedEquipment.length === 0) {
                alert('请选择要销库的设备');
                return;
            }
            
            // 显示确认对话框
            if (!confirm(`确认要销库选中的 ${selectedEquipment.length} 台设备吗？`)) {
                return;
            }
            
            // 显示加载状态
            $('#searchStatus').html('<div class="alert alert-info">正在处理销库请求...</div>');
            
            $.ajax({
                url: '/confirm_discard',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    equipment_list: selectedEquipment
                }),
                success: function(response) {
                    if (response.success) {
                        $('#searchStatus').html(`
                            <div class="alert alert-success">
                                ${response.message}<br>
                                页面将在3秒后刷新...
                            </div>
                        `);
                        setTimeout(() => {
                            location.reload();
                        }, 3000);
                    } else {
                        $('#searchStatus').html(`
                            <div class="alert alert-danger">
                                ${response.message}
                            </div>
                        `);
                    }
                },
                error: function(xhr) {
                    const error = xhr.responseJSON || { message: '销库失败，请重试' };
                    $('#searchStatus').html(`
                        <div class="alert alert-danger">
                            ${error.message}
                        </div>
                    `);
                    console.error('Error:', error);
                }
            });
        });
    });
</script>
{% endblock %} 